window.$ = function(obj) {
	return typeof(obj) == "string" ? document.getElementById(obj) : obj
}
window.decode = function(responseText){
	return eval('('+responseText+')');
}

String.prototype.trim = function() {   
    return this.replace(/^\s+/g,"").replace(/\s+$/g,"");   
}

String.prototype.getRealLength = function() {
    var realLength = 0, len = this.length, charCode = -1;
    for (var i = 0; i < len; i++) {
        charCode = this.charCodeAt(i);
        if (charCode >= 0 && charCode <= 128) realLength += 1;
        else realLength += 2;
    }
    return realLength;
}

function getScript(str) {
    var matchAll = new RegExp('(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)', 'img');   
    var matchOne = new RegExp('(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)', 'im');   
    
    var a = str.match(matchAll) || [];   
    var result = [];
    for(var i=0; i<a.length; i++){
        result.push((a[i].match(matchOne) || ['', ''])[1]);   
    }
    return result;
}   

function evalScript(str) {
    var scripts = getScript(str);
    for(var i=0; i < scripts.length; i++){
        eval(scripts[i]);
    }
}   

function reloadWorkspace() {
    self.location.href = "/jsp/main/index_frameset.jsp";
}

function toPortal(id,forceOpen,userCurrKey){
	if(forceOpen){
		forceOpen = true;
	}else{
		forceOpen = false;
	}
	var url = "/jsp/main/workspace.jsp?opt=addOrUpdate";
	if(userCurrKey != true){
		url += "&key=mainpage";
	}
	url+="&forceOpen="+forceOpen;
	url+="&id="+id;
	self.location.href = url;
}

function toRes(selectedPaths, target) {
    var url = "/jsp/main/workspace.jsp?opt=addOrUpdate&key=menu.{1}monitor.{1}res";
    if(selectedPaths) {
        url += "&selectedPaths="+selectedPaths;
    }

    if(target=='parent') {
        parent.location.href = url;
    } else {
        self.location.href = url;
    }
}

function toService(path, target) {
    var url = "/jsp/main/workspace.jsp?opt=addOrUpdate&key=menu.{1}monitor.{2}bizz";
    if(path) {
        url += "&selectedPaths="+path+",";
    }
    
    if(target=='parent') {
        parent.location.href = url;
    } else {
        self.location.href = url;
    }
}

function toDep(path, target) {
    var url = "/jsp/main/workspace.jsp?opt=addOrUpdate&key=menu.{1}monitor.{6}monitorMana.{3}dep";
    if(path) {
        url += "&selectedPaths="+path+",";
    }
    
    if(target=='parent') {
        parent.location.href = url;
    } else {
        self.location.href = url;
    }
}

function toCustomTopo(path, target) {
    var url = "/jsp/main/workspace.jsp?opt=addOrUpdate&key=menu.{3}topology.{1}custom";
    if(path) {
        url += "&initPath="+path;
    }
    
    if(target=='parent') {
        parent.location.href = url;
    } else {
        self.location.href = url;
    }
}

function toEvent(selectedIds, target,servicePath,serviceName) {
    var url = "/jsp/main/workspace.jsp?opt=addOrUpdate&key=menu.{2}event.{0}currentEvent";
    if(selectedIds) {
        url += "&selectedIds="+selectedIds;
    }
    
    if(servicePath){
    	url += "&servicePath="+servicePath;
    }
    
    if(serviceName){
    	url += "&service="+serviceName;
    }


    if(target=='parent') {
        parent.location.href = url;
    } else {
        self.location.href = url;
    }
}

function toServiceTopo(path, target) {
    var url = "/jsp/main/workspace.jsp?opt=addOrUpdate&key=menu.{3}topology.{2}service";
    if(path) {
        url += "&initPath="+path;
    }

    if(target=='parent') {
        parent.location.href = url;
    } else {
        self.location.href = url;
    }
}

function justWindowHeight(objName) {
    var tableName = 'dArticleList';
    if(objName) {
        tableName = objName;
    } 
    if($(tableName)) {
	    $(tableName).style.height = document.body.clientHeight-55;
	    $(tableName).height = document.body.clientHeight-55;
    }
}

function getElementLeft(element){
	var actualLeft = element.offsetLeft;
	var current = element.offsetParent;
	while (current !== null){
		actualLeft += current.offsetLeft;
		current = current.offsetParent;
	}
	return actualLeft;
}

function getElementTop(element){
	var actualTop = element.offsetTop;
	var current = element.offsetParent;
	while (current !== null){
	    actualTop += current.offsetTop;
	    current = current.offsetParent;
	}
	return actualTop;
}

function post_to_url(path, params, method) { 
    method = method || "post";
    var form = document.createElement("form"); 
    form.setAttribute("method", method); 
    form.setAttribute("action", path); 
    for(var key in params) { 
        var hiddenField = document.createElement("input"); 
        hiddenField.setAttribute("type", "hidden"); 
        hiddenField.setAttribute("name", key); 
        hiddenField.setAttribute("value", params[key]); 
        form.appendChild(hiddenField); 
    } 
    document.body.appendChild(form); 
    form.submit(); 
} 

PigossWindow = {
	mini_height : 100,
	mini_width : 200,
	default_taget : 'newwindow',
	default_show_toolbar : 'no',
	default_show_menubar : 'no',
	default_resizable : 'no',
	default_show_location : 'no',
	
	SIZE_MINI_WINDOW : 0,
	SIZE_LARGE_WINDOW : 1,
	
	showFullScreen : function(url){
		window.open (url, "", 'fullscreen=1,top=0,left=0,toolbar=no,scrollbars=yes,resizable=no,location=no,directories=0,status=no')
	},
	show : function(url,size,target,width,height){
		if(!target){
			target = this.default_taget;
		}
		if(!width){
			width =  this.mini_width;
		}
		if(!height){
			height =  this.mini_height;
		}
		if(size!=undefined && size == this.SIZE_LARGE_WINDOW){
			width = document.body.clientWidth;
			height = document.body.clientHeight;
		}
		var top = (window.screen.availHeight-height)/2;
  		var left = (window.screen.availWidth-width)/2;  
		window.open (url, "", 'width='+width+', height='+height+',top='+top+',left='+left+',toolbar=no,scrollbars=yes,titlebar=no,resizable=yes,location=no,directories=0,status=no')
	},
    showWithPost : function(url,params,size,target,width,height){
		var formEl = document.createElement("form");
		formEl.method = "post";
		formEl.action = url;
		formEl.target = target;
		
		for(p in params) {
			var inEl = document.createElement("input");
			inEl.type="text";
			inEl.name = p;
			inEl.value = params[p];
			formEl.appendChild(inEl);
			window.alert(inEl.value);
		}
	    PigossWindow.show(url,size,target,width,height);
        document.body.appendChild(formEl);
        formEl.submit();
    }
}

AjaxUtil = {
	activeX : ['MSXML2.XMLHTTP.3.0',
	           'MSXML2.XMLHTTP',
	           'Microsoft.XMLHTTP'],
	request : function(config){
	   if(config.showLoading) {
	       var msg = config.showLoading;
	       if(typeof(msg)=="string") {
	           loadingBox = PigossMsg.loading(msg);
	       } else {
               loadingBox = PigossMsg.loading();
           }
	   }
	
		var requestConfig =  {
			url : '',
			header : {
				'Content-Type' : 'application/x-www-form-urlencoded',
				'If-Modified-Since' : '0'
			},
			method : 'POST',
			params : null,
			success : function(responseText,statusCode){},
			failure : function(responseText,statusCode){}
		}
		for(p in requestConfig){
			if(config[p]){
				requestConfig[p] = config[p];
			}
		}
		if(config.useCache) {
		      delete requestConfig.header['If-Modified-Since'];
		}
		
		var httpConn = this.createXhrObject();
	//	var breakTimeout = setTimeout(function(){httpConn.abort();}, 40000); 
		httpConn.open(requestConfig.method,requestConfig.url,true);
		for(p in requestConfig.header){
			httpConn.setRequestHeader(p,requestConfig.header[p]);
		}
		httpConn.onreadystatechange = function(){
			if(httpConn.readyState == 4){
                if(config.showLoading) {
                    if(loadingBox) {
                        loadingBox.loadingEnd();
                    }
                }
				if(httpConn.status == 200){
					if(requestConfig.success){
						requestConfig.success(httpConn.responseText,httpConn.status);
					}
				}else{
					alert("ll="+httpConn.status);
					var doFailure = true;
                    if(httpConn.status==12029){
                    	if(window.top.userinfo.currTimeout == null){
                    		window.top.userinfo.currTimeout = new Date().getTime();
                    	}
                    	var currIsPortalUser = (window.top.userinfo && window.top.userinfo.isPortalUser);
                    	if(!currIsPortalUser || (window.top.userinfo.currTimeout!=null && (new Date().getTime() - window.top.userinfo.currTimeout) > window.top.userinfo.maxTimeout)){
                    		window.top.responseNull("code="+httpConn.status);
                    	}else{
                    		doFailure = false;
                    	}
                        httpConn = null;
			            return;
                    } 
					if(requestConfig.failure){
						if(doFailure){
							requestConfig.failure(httpConn.responseText,httpConn.status);
						}
					}
				}
//				clearTimeout(breakTimeout);
                httpConn = null;
			}	
		}
		var paraStr = this.encodeParam(requestConfig.params);
		httpConn.send(paraStr);
	},
	
	//private
	encodeParam : function(obj){
		if(obj == undefined || obj == null){
			return "";
		}
		var paraStr = "";
		for(p in obj){
			paraStr = this.addParam(paraStr,p,obj[p]);
		}
		return paraStr;
	},
	
	//private 
	addParam : function(paraStr,paramName,paramValue){
	   paramValue += "";
	   paramValue = paramValue.replace(/%/g,"%25");
       paramValue = paramValue.replace(/\&/g,"%26");
       paramValue = paramValue.replace(/\+/g,"%2B");
	
		paraStr += paraStr.length > 0 ? "&" : "";
		paraStr += paramName + "=" + paramValue;
		return paraStr;
	},
	
	 // private
	createXhrObject : function() {
		var http;
	    try {
	        http = new XMLHttpRequest();             
	    } catch(e) {
	        for (var i = 0; i < this.activeX.length; i++) {	            
	            try {
	                http = new ActiveXObject(this.activeX[i]); 
	                break;
	            } catch(e) {}
	        }
	    } finally {
	        return http;
	    }
	}
};

var rightConstant = {
	LOOK_ONLY : 1,
	LOOK_OPT : 2,
	LOOK_OPT_MANA : 3
};

function saveUserContextParam(key,val){
	AjaxUtil.request({
		url : '/userJsp_updateUserContextParam.action',
		params : {
			key : key,
			val : val
		}
	});
}





function MouseDownToResize(obj){ 
	setTableLayoutToFixed(); 
	obj.mouseDownX=event.clientX; 
	obj.pareneTdW=obj.parentElement.offsetWidth; 
	obj.pareneTableW=dArticleList.offsetWidth; 
	obj.setCapture(); 
} 
function MouseMoveToResize(obj){ 
	if(!obj.mouseDownX) return false; 
	var newWidth=obj.pareneTdW*1+event.clientX*1-obj.mouseDownX; 
	if(newWidth>0) 
	{ 
		obj.parentElement.style.width = newWidth; 
		//dArticleList.style.width=obj.pareneTableW*1+event.clientX*1-obj.mouseDownX; 
	} 
} 
function MouseUpToResize(obj){ 
	obj.releaseCapture(); 
	obj.mouseDownX=0; 
} 
function setTableLayoutToFixed() 
{ 
    var dArticleList = document.getElementById("dArticleList");
	if(dArticleList.style.tableLayout=='fixed') return; 
	var headerTr=dArticleList.rows[0]; 
	for(var i=0;i<headerTr.cells.length;i++) 
	{ 
		headerTr.cells[i].styleOffsetWidth=headerTr.cells[i].offsetWidth; 
	} 
	 
	for(var i=0;i<headerTr.cells.length;i++) 
	{ 
		headerTr.cells[i].style.width=headerTr.cells[i].styleOffsetWidth; 
	} 
	dArticleList.style.tableLayout='fixed'; 
} 


function onClickDIVOne(DivId){
    if(document.getElementById(DivId).style.display=='none'){
        document.getElementById(DivId).style.display='';
    }else{
        document.getElementById(DivId).style.display='none';
    }
}

function onClickDIV(DivId1,DivId2){
    document.getElementById(DivId1).style.display='';
    document.getElementById(DivId2).style.display='none';
}


function checkBeforeOfUploadOrImport(file,type,DIVID,file2){
	if(file2 == undefined){
		file2 = '';
	}
	var fileName = document.getElementById(file).value;
	var typeOfFile = fileName.substr(fileName.lastIndexOf(".")).toLowerCase();
	if(type == 'image'){
		if(typeOfFile == '.jpg' || typeOfFile == '.gif' || typeOfFile == '.bmp' || typeOfFile == '.png' || typeOfFile == '.jpeg'){
			if(file2 != ''){
				var fileName2 = document.getElementById(file2).value;
				if(fileName2 != ''){
					var typeOfFile2 = fileName2.substr(fileName2.lastIndexOf(".")).toLowerCase();
					if(typeOfFile2 == '.jpg' || typeOfFile2 == '.gif' || typeOfFile2 == '.bmp' || typeOfFile2 == '.png' || typeOfFile2 == '.jpeg'){
						$(DIVID).style.display = 'none';
					}else{
						$(DIVID).style.display = 'block';
						$(DIVID).innerHTML = "<font color=red>"+Uploader.checkFailedHint.replace("${0}",".jpg ,.gif ,.bmp ,.png ,.jpeg")+typeOfFile2+"</font>";
					}
				}
			}
		}else{
			$(DIVID).style.display = 'block';
			$(DIVID).innerHTML = "<font color=red>"+Uploader.checkFailedHint.replace("${0}",".jpg ,.gif ,.bmp ,.png ,.jpeg")+typeOfFile+"</font>";
		}
	}else if(type == '.txt'){
		if(typeOfFile == '.txt'){
			$(DIVID).style.display = 'none';
		}else{
			$(DIVID).style.display = 'block';
			$(DIVID).innerHTML = "<font color=red>"+Uploader.checkFailedHint.replace("${0}",".txt")+typeOfFile+"</font>";
		}
	}else if(type == 'Excel'){
		if(typeOfFile == '.xls' || typeOfFile == '.xlsx'){
			(DIVID).style.display = 'none';
		}else{
			$(DIVID).style.display = 'block';
			$(DIVID).innerHTML = "<font color=red>"+Uploader.checkFailedHint.replace("${0}",".xls,.xlsx")+typeOfFile+"</font>";
		}
	} 
};



